package cn.tedu.sentinel01.controller;

import cn.tedu.sentinel01.service.HelloService;
import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@Slf4j
public class HelloController {
    @Autowired
    HelloService helloService;

    @GetMapping("/hello")
    public String sayHi(String name){
        // 判断资源是否符合规则
        Entry entry=null;
//       SphU.entry()方法检查sayHi资源有没有违反任何规则
        try {
            entry = SphU.entry("sayHi");
            String result = helloService.sayHi(name);
            return result;
//如果违反了就抛出异常BlockException，没有违反就继续向后执行
        } catch (BlockException e) {
           log.info("当前资源sayHi收到了限制",e);
        }finally {
            if (entry!=null){
//                资源关闭
                entry.close();
            }
        }
        return "你被限流了";

    }
}
